import { useEffect, useState } from 'react'
import Taro, { FC, useRouter } from '@tarojs/taro'
import { firstValueFrom, Subject, Subscription } from 'rxjs';
import { debounceTime, map, switchMap } from 'rxjs/operators';
import { AtList, AtListItem, AtModal, AtModalAction, AtModalContent, AtModalHeader, AtTextarea } from "taro-ui"
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import { View, Text, Image, Textarea, ScrollView, Button } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 

import { useMsgFacade } from '@/hooks/useMsgFacade';
import { MUTE_STATUS, ROOMSTATS_TYPE, ROOM_ROLE } from '@/constants/room';
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { formatTimeLite, numFormat } from '@/utils';
import Login from '@/components/loginPopup';
import { getLogger } from '@/utils/log';
import { EditRoomParams } from '@/models/request/roomReq';
import { onEmit } from '@/utils/rxHelpers';
import ChannelStyle from '@@/channel/channelStyle'

import './index.scss';
import { useRoomFacade } from './useRoomFacade';

//评论与互动
export const Chat: FC = () => {

  const logger = getLogger("/pages/liveRoom/Chat");

  //导入门面的所有元素作为页面绑定
  const [roomFacade, roomRole, ownerId, anchorId, assistants, likes, tips, muteStatus] = useRoomFacade();
  const [authFacade, loginStatus, userId, realName, orgs, userInfo, userApproveStatus, orgApproveStatus] = useAuthFacade();

  // const avatarImg = 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/tx.png'
  const avatarImg = ASSETS_PATH + '/default_avator.png'

  //具有管理权限的角色
  const admins = [ROOM_ROLE.ANCHOR, ROOM_ROLE.OWNER_ANCHOR, ROOM_ROLE.OWNER_ASSISTANT, ROOM_ROLE.ASSISTANT];

  const isAdmin = (uid: string) => {
    const adminArr = assistants.map(assistant => {
      return assistant.userId;
    })
    adminArr.push(ownerId);

    if (anchorId) adminArr.push(anchorId);

    if (adminArr.includes(uid)) {
      return true;
    } else {
      return false;
    }
  }
  const router = useRouter();
  const roomId = router.params.roomId || "";
  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState(initSubject);

  const defaultTip = tips || `欢迎来到${ChannelStyle.appName}LIVE,请不要发布色情、违法、低俗、侵权等法律禁止的內容信息,健康参与。`
  const [msgFacade, msgList] = useMsgFacade();
  const [inputVal, setInputVal] = useState("");
  const [keyboardHeight, setKeyboardHeight] = useState(0)
  const [showInput, setShowInput] = useState(false)//显示/隐藏输入文本框
  const [like, setLike] = useState(false) //点赞判断
  const [editTips, setEditTips] = useState(false)//修改公告提示框
  const [inputTipsVal, setInputTipsVal] = useState("");  //公告输入的值
  const [showContent, setShowContent] = useState(false)//是否显示踢出房间禁言按钮
  const [kickLive, setKickLive] = useState(false)//踢出房间提示
  const [idVal, setIdVal] = useState("");  //相对应的用户id
  const [forbiddenWd, setForbiddenWd] = useState(false)//禁言提示框
  const [forbiddenVal, setForbiddenVal] = useState({
    groupId: '',
    userId: '',
    muteTime: 0
  })//禁言接收的参数

  const [status, setStatus] = useState(1)//成员状态，1是正常，2是禁言，3是已踢出

  //登录弹窗组件相关状态
  const [clicked, setClicked] = useState(false);

  //隐藏输入框
  const hideInput = () => {
    setClicked(true);
    //需要再登录成功后重新点击一次
    if (loginStatus === true) {
      setShowInput(!showInput)
    }
  }

  //隐藏/显示公告提示框
  const setTipsShow = () => {
    setEditTips(!editTips)
  }

  //隐藏踢出房间提示框
  const setKick = () => {
    setKickLive(false)
  }

  //显示踢出房间提示框
  const openModel = (value) => {
    if (status === 3) {
      Taro.showToast({
        title: '该用户已被踢出直播间',
        icon: 'none',
        duration: 3000
      })
    } else {
      console.log('value的值为：', value)
      setKickLive(true)
      setIdVal(() => value)
    }
  }

  //确认踢出房间
  const kickOut = () => {
    msgFacade.kickMember(idVal)
    setKickLive(false)
    setStatus(3);
  }

  //隐藏禁言提示框
  const setForbid = () => {
    setForbiddenWd(false)
  }

  //显示禁言提示框
  const openForbidModel = ({ value1, value2, value3 }) => {
    if (status === 2) {
      Taro.showToast({
        title: '该用户已经被禁言',
        icon: 'none',
        duration: 3000
      })
    } else if (status === 3) {
      Taro.showToast({
        title: '该用户已经被踢出房间',
        icon: 'none',
        duration: 3000
      })
    } else {
      setForbiddenWd(true)
      setForbiddenVal(() => ({ groupId: value1, userId: value2, muteTime: value3 }))
    }
  }

  //确认禁言用户
  const forbiddenUser = () => {
    console.log('禁言参数：', forbiddenVal)
    msgFacade.muteGroupMember(forbiddenVal.groupId, forbiddenVal.userId, forbiddenVal.muteTime)
    setForbiddenWd(false)
  }

  //查询群成员的资料
  const getMemberVal = async (value1: string, value2: string[]) => {
    setShowContent(!showContent)
    try {
      const res = await msgFacade.getMemberInfo(value1, value2);
      const member = res.data.memberList[0];
      console.log('查询群成员的资料：', member)
      if (member.muteUntil > new Date().getTime() / 1000) {
        setStatus(2)
      }
    } catch (error) {
      console.error("获取数据出错:", error);
      setStatus(3);
    }
  }

  //获取输入框高度
  const getInputTipsVal = (val: string) => {
    setInputTipsVal(val);
  }

  //发送聊天信息
  const sendRoomMsg = () => {
    //TODO 字符串过滤
    const msg = inputVal.replace(/(^\s*)|(\s*$)/g, "");

    if (msg.length === 0) {
      Taro.showToast({
        title: '不能输入空文本...',
        icon: 'none',
        duration: 3000
      })
      return;
    }

    msgFacade.sendRoomTextMsg(msg)
      .then((res: any) => {
        //发送成功后清空输入框
        setInputVal("");
      })
  }


  const getInputVal = (e: any) => {
    const text = e.detail.value;
    setInputVal(text);
  }

  //键盘弹起高度设置
  const getKeyboardHeight = (e) => {
    setKeyboardHeight(e.mpEvent.detail.height)
  }

  const onKeyboardheightchange = (e) => {
    Taro.onKeyboardHeightChange(res => {
      setKeyboardHeight(res.height)
    })
  }

  //点赞操作
  const clickLike = () => {
    setLike(true)
    setTimeout(() => {
      setLike(false)
    }, 1000);
    firstValueFrom(roomFacade.saveRoomStat(roomId, ROOMSTATS_TYPE.LIKED));
    firstValueFrom(roomFacade.updateEtcData(roomId, { likes: 5 }));
  }
  //跳转页面
  const toChatList = () => {
    Taro.navigateTo({
      // url: '/pages/liveRoom/chatList/index'
      url: '/subPages/liveRoom/chatList/index'
    })
  }

  const submit = () => {
    emitter.next({
      roomId,
      tips: inputTipsVal
    } as EditRoomParams)
  }

  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<any>(
        emitter.asObservable()
          .pipe(
            //防抖动(防重复)
            debounceTime(500),
            map(obj => obj as EditRoomParams),
            //接收按钮点击的参数 
            switchMap(roomFacade.editRoomTips)
          ),
        () => {
          Taro.showToast({
            title: '修改成功',
            icon: 'none',
            duration: 2000
          });
          setEditTips(false)
        },
        err => {
          logger.ERROR("保存信息失败！", err)
          setEmitter(initSubject);
        }
      ),
    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])


  return (
    <ScrollView scrollY>
      <View className='index'>
        <View className='main'>
          <AtList>
            <AtListItem title='公告' note={tips || defaultTip} onClick={() => {
              admins.includes(roomRole) && setTipsShow();
            }}
            />
          </AtList>
          {
            msgList.map((msg, index) => {
              return msg.from !== "administrator" && (
                <View className='box1' key={String(index)} onClick={() => getMemberVal(msg.to, [msg.from])}>
                  <View className='box1-left'>
                    <Image src={msg.avatar == '' ? avatarImg : msg.avatar} className='tx_img'></Image>
                  </View>
                  <View className='box1-right'>
                    <View className='top'>
                      <View className='top-left'>
                        <View className='name'> {msg.nick}</View>
                        <View className='role' style={{ display: isAdmin(msg.from) ? 'block' : 'none' }}>管理员</View>
                      </View>
                      <Text className='time'>{formatTimeLite(new Date(msg.time * 1000))}</Text>
                      {
                        //本消息发言人不属于创建人或主播，并且当前用户是管理员
                        (msg.from !== ownerId || (anchorId && msg.from !== anchorId)) && admins.includes(roomRole) && msg.from !== userId && (
                          <View className='show'><Image src={showContent ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/up.png' : 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/down.png'} className='show_img'></Image></View>
                        )
                      }
                    </View>
                    <View className='text'>
                      <Text className='msgText'>{!msg.isRevoked ? msg.payload.text : "消息已被撤回."}</Text>
                    </View>
                    <View className='butt'>
                      {
                        //本消息发言人不属于创建人或主播，并且当前用户是管理员
                        (msg.from !== ownerId || (anchorId && msg.from !== anchorId)) && admins.includes(roomRole) && msg.from !== userId && showContent && (
                          <View>
                            <Text className={status === 3 ? 'text3' : 'text2'} onClick={() => openModel(msg.from)}>踢出房间</Text>
                            <Text className={(status === 2 || status === 3) ? 'text3' : 'text2'} onClick={() => openForbidModel({ value1: msg.to, value2: msg.from, value3: 8 * 3600 })} >禁言</Text>
                          </View>
                        )
                      }
                      {/* {(userId === msg.from || !isAdmin(msg.from)) && !msg.isRevoked && (
                        <View>
                          <Text className='text2' onClick={() => msgFacade.revokeMessage(msg)}>撤回评论</Text>
                        </View>
                      )} */}
                    </View>
                  </View>
                </View>
              )
            }
            )
          }
        </View>
        <View className='foot'>
          <View className='foot-left'>
            {
              //主播端观看页面
              admins.includes(roomRole) && (
                <View className={muteStatus === 2 ? " bottom" : "bottom2"} >
                  <View className='input' onClick={hideInput}>这里发言..</View>
                </View>
              )
            }

            {
              //观众端观看页面
              roomRole === ROOM_ROLE.AUDIENCE && (
                <View className='bottom1'>
                  <View className='input1' onClick={hideInput}>这里发言..</View>
                </View>
              )
            }

            {
              //键盘输入框
              showInput && (
                <View className='inputMsg' style={{ 'bottom': keyboardHeight }}>
                  <View className='input-box'>
                    <Textarea className='input-text'
                      maxlength={80}
                      cursorSpacing={90}
                      fixed
                      value={inputVal}
                      onInput={getInputVal}
                      showConfirmBar={false}
                      adjustPosition={false}
                      placeholder='发一条友善的评论吧...'
                      confirm-type='send'
                      onConfirm={sendRoomMsg}
                      onBlur={hideInput}
                      onFocus={getKeyboardHeight}
                      autoFocus
                      onKeyboardHeightChange={onKeyboardheightchange}
                    />
                  </View>
                  <View className='send-bnt' onClick={sendRoomMsg}>发送</View>
                </View>
              )}
          </View>

          {(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
            <View className='foot-right' >
              {
                muteStatus === MUTE_STATUS.PENDING && (
                  <View className='partPass' onClick={toChatList}>
                    <Image src={ASSETS_PATH + '/batch_selection.png'} className='part_img' ></Image>
                    <View className='part'>批量放行</View>
                  </View>
                )
              }
              <View className='notic' onClick={setTipsShow}>
                <Image src={ASSETS_PATH + '/notice.png'} className='notic_img' ></Image>
                <View className='noticText'>公告</View>
              </View>
              <View className='ider'>
                <Image src={like ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/active.gif' : ASSETS_PATH + '/live_Likes.png'} className='ider_img' onClick={clickLike} ></Image>
                <View className='inputBox'>
                  <View className='shuzi'>{numFormat(likes)}</View>
                </View>
              </View>
            </View>
          )
          }

          {
            //观众端观看页面点赞
            roomRole === ROOM_ROLE.AUDIENCE && (
              <View className='foot-right'>
                <View className='ider1'>
                  <Image src={like ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/active.gif' : ASSETS_PATH + '/live_Likes.png'} className='ider_img' onClick={clickLike} ></Image>
                  <View className='inputBox'>
                    <View className='shuzi'>{numFormat(likes)}</View>
                  </View>
                </View>
              </View>
            )
          }
        </View>
        {editTips && (
          <AtModal isOpened={editTips}>
            <AtModalHeader>修改公告</AtModalHeader>
            <AtModalContent>
              <AtTextarea
                className='tipsInput'
                maxLength={50}
                value={inputTipsVal}
                onChange={getInputTipsVal}
                placeholder={`欢迎来到${ChannelStyle.appName}LIVE，请不要发布色情、违法、低俗、侵权等法律禁止的内容信息，健康参与。`}
              />
            </AtModalContent>
            <AtModalAction> <Button onClick={setTipsShow}>取消</Button> <Button onClick={submit} >确定</Button> </AtModalAction>
          </AtModal>
        )}
        <Login clicked={clicked} setClicked={setClicked} />

        {/* 主播踢出房间，禁言提示框 */}
        <AtModal
          className='model'
          isOpened={kickLive}
          cancelText='取消'
          confirmText='确认'
          onCancel={setKick}
          onConfirm={kickOut}
          content='确认要将该用户踢出直播间吗?'
        />

        {/* 主播禁言用户提示框 */}
        <AtModal
          className='model'
          isOpened={forbiddenWd}
          cancelText='取消'
          confirmText='确认'
          onCancel={setForbid}
          onConfirm={forbiddenUser}
          content='确认要将该用户禁言吗?'
        />
      </View>
    </ScrollView>
  )
}

export default Chat

